package com.breeze.blockchain.service;

import cn.hutool.core.util.NumberUtil;
import com.breeze.blockchain.common.enums.SettingKeyEnum;
import com.breeze.blockchain.mybatis.entity.SettingDo;
import com.breeze.components.core.exception.ApiException;
import com.breeze.components.core.exception.error.ErrorCodeInterface;
import com.mybatisflex.core.service.IService;
import java.math.BigDecimal;
import java.util.Optional;

/**
 * 配置表 服务层。
 *
 * @author breeze
 * @since 2024-05-11 23:21:51
 */
public interface SettingService extends IService<SettingDo> {

  SettingDo getKeyByValue(String key);

  Optional<SettingDo> getKeyByValueOpt(String key);

  Optional<String> getKeyValue(SettingKeyEnum setting);

  void putCache(SettingDo setting);

  @SuppressWarnings("UnusedReturnValue")
  boolean addOrUpdate(SettingDo setting);

  default BigDecimal getDecimalKeyValue(SettingKeyEnum setting, BigDecimal defaultValue) {
    return getKeyValue(setting).map(BigDecimal::new).orElse(defaultValue);
  }

  default BigDecimal getDecimalKeyValueThrow(SettingKeyEnum setting, ErrorCodeInterface errorCode) {
    return getKeyValue(setting).map(BigDecimal::new).orElseThrow(() -> new ApiException(errorCode));
  }

  default int getIntegerKeyValue(SettingKeyEnum setting, Integer defaultValue) {
    return getKeyValue(setting)
        .filter(NumberUtil::isNumber)
        .map(Integer::valueOf)
        .orElse(defaultValue);
  }

  default int getIntegerKeyValue(SettingKeyEnum setting, ErrorCodeInterface errorCode) {
    return getKeyValue(setting)
        .filter(NumberUtil::isNumber)
        .map(Integer::valueOf)
        .orElseThrow(() -> new ApiException(errorCode));
  }

  default boolean getBooleanKeyValue(SettingKeyEnum setting, Boolean defaultValue) {
    return getKeyValue(setting).map(Boolean::valueOf).orElse(defaultValue);
  }

  default boolean getBooleanKeyValueThrow(SettingKeyEnum setting, ErrorCodeInterface errorCode) {
    return getKeyValue(setting)
        .map(Boolean::valueOf)
        .orElseThrow(() -> new ApiException(errorCode));
  }

  default Long getLongKeyValue(SettingKeyEnum setting, Long defaultValue) {
    return getKeyValue(setting).map(Long::valueOf).orElse(defaultValue);
  }

  default Long getLongKeyValueThrow(SettingKeyEnum setting, ErrorCodeInterface errorCode) {
    return getKeyValue(setting).map(Long::valueOf).orElseThrow(() -> new ApiException(errorCode));
  }

  default String getStringKeyValue(SettingKeyEnum privilegeTaskOpen, String defaultVal) {
    return getKeyValue(privilegeTaskOpen).orElse(defaultVal);
  }

  default String getStringKeyValueThrow(
      SettingKeyEnum privilegeTaskOpen, ErrorCodeInterface errorCode) {
    return getKeyValue(privilegeTaskOpen).orElseThrow(() -> new ApiException(errorCode));
  }
}
